/**
 * Copyright (C) 2013-2014 EaseMob Technologies. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *     http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.hengtiansoft.lfy.chart.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewTreeObserver;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;

import com.hengtiansoft.lfy.base.BaseActivity;
import com.hengtiansoft.lfy.chart.applib.controller.HXSDKHelper;
import com.hengtiansoft.lfy.R;
import com.hengtiansoft.lfy.chart.adapter.GroupAdapter;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMGroup;
import com.hyphenate.util.EMLog;

import java.util.List;

/**
 * 群组页面
 */
public class GroupsActivity extends BaseActivity {
    public static final String TAG = "GroupsActivity";
    private ListView groupListView;
    protected List<EMGroup> grouplist;
    private GroupAdapter groupAdapter;
    private InputMethodManager inputMethodManager;
    public static GroupsActivity instance;
    private SyncListener syncListener;
    private View progressBar;
    Handler handler = new Handler();
    ImageButton clearSearch;
    EditText query;
    private LinearLayout mLlHint;
    private boolean hideEnter = false;
    class SyncListener implements HXSDKHelper.HXSyncListener {
        @Override
        public void onSyncSucess(final boolean success) {
            EMLog.d(TAG, "onSyncGroupsFinish success:" + success);
            runOnUiThread(new Runnable() {
                public void run() {
                    if (success) {
                        handler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                refresh();
                                progressBar.setVisibility(View.GONE);
                            }
                        }, 1000);
                    } else {
                        if (!GroupsActivity.this.isFinishing()) {
                            String s1 = getResources()
                                    .getString(
                                            R.string.Failed_to_get_group_chat_information);
                            Toast.makeText(GroupsActivity.this, s1,
                                    Toast.LENGTH_LONG).show();
                            progressBar.setVisibility(View.GONE);
                        }
                    }
                }
            });
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_groups);

        instance = this;
        inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        grouplist = EMClient.getInstance().groupManager().getAllGroups();
        groupListView = (ListView) findViewById(R.id.list);

        // swipeRefreshLayout = (SwipeRefreshLayout)
        // findViewById(R.id.swipe_layout);
        // swipeRefreshLayout.setColorSchemeResources(
        // android.R.color.holo_blue_bright,
        // android.R.color.holo_green_light,
        // android.R.color.holo_orange_light,
        // android.R.color.holo_red_light);
        // swipeRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
        //
        // @Override
        // public void onRefresh() {
        // swipeRefreshLayout.setRefreshing(false);
        // asyncFetchGroupsFromServer();
        // }
        // });
        mLlHint = (LinearLayout) findViewById(R.id.ll_hint);
        // 搜索框
        query = (EditText) findViewById(R.id.query);
        clearSearch = (ImageButton) findViewById(R.id.search_clear);
        query.addTextChangedListener(new TextWatcher() {
            public void onTextChanged(CharSequence s, int start, int before,
                                      int count) {
                groupAdapter.getFilter().filter(s);
                if (s.length() > 0) {
                    mLlHint.setVisibility(View.GONE);
                    clearSearch.setVisibility(View.VISIBLE);
                } else {
                    mLlHint.setVisibility(View.VISIBLE);
                    clearSearch.setVisibility(View.INVISIBLE);

                }
            }

            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {
            }

            public void afterTextChanged(Editable s) {
            }
        });
        clearSearch.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                query.getText().clear();
                hideSoftKeyboard();
            }
        });
        groupAdapter = new GroupAdapter(this, 1, grouplist);
        groupListView.setAdapter(groupAdapter);
        groupListView.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
//                if (position == 0) {
//                    // 新建群聊
//                    startActivityForResult(new Intent(GroupsActivity.this,
//                            NewGroupActivity.class), 0);
//                }
//                // else if (position == 2) {
//                // // 添加公开群
//                // startActivityForResult(new Intent(GroupsActivity.this,
//                // PublicGroupsActivity.class), 0);
//                // }
//                else {
                    // 进入群聊
                    Intent intent = new Intent(GroupsActivity.this,
                            ChatActivity.class);
                    // it is group chat
                    intent.putExtra("chatType", ChatActivity.CHATTYPE_GROUP);
                    intent.putExtra("groupId",
                            groupAdapter.getItem(position).getGroupId());
                    startActivityForResult(intent, 0);
               // }
            }

        });
        groupListView.setOnTouchListener(new OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (getWindow().getAttributes().softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN) {
                    if (getCurrentFocus() != null)
                        inputMethodManager.hideSoftInputFromWindow(
                                getCurrentFocus().getWindowToken(),
                                InputMethodManager.HIDE_NOT_ALWAYS);
                }
                return false;
            }
        });

        progressBar = (View) findViewById(R.id.progress_bar);

        syncListener = new SyncListener();
        HXSDKHelper.getInstance().addSyncGroupListener(syncListener);

        if (!HXSDKHelper.getInstance().isGroupsSyncedWithServer()) {
            progressBar.setVisibility(View.VISIBLE);
        } else {
            progressBar.setVisibility(View.GONE);
        }

        refresh();
        getWindow().getDecorView().getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                Rect rect = new Rect();
                //获取root在窗体的可视区域
                getWindow().getDecorView().getWindowVisibleDisplayFrame(rect);
                //获取root在窗体的不可视区域高度(被其他View遮挡的区域高度)
                int rootInvisibleHeight = getWindow().getDecorView().getRootView().getHeight() - rect.bottom;
                if (rootInvisibleHeight < 300) {
                    if(hideEnter) {
                        getWindow().getDecorView().requestFocus();
                        hideEnter=false;
                    }
                }else{

                    hideEnter=true;
                }
            }
        });
    }

    void hideSoftKeyboard() {
        if (getWindow().getAttributes().softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN) {
            if (getCurrentFocus() != null)
                inputMethodManager.hideSoftInputFromWindow(getCurrentFocus()
                        .getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    /**
     * 进入公开群聊列表
     *
     */
    public void onPublicGroups(View view) {
//        startActivity(new Intent(this, PublicGroupsActivity.class));
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onResume() {
        super.onResume();
        grouplist = EMClient.getInstance().groupManager().getAllGroups();
        groupAdapter = new GroupAdapter(this, 1, grouplist);
        groupListView.setAdapter(groupAdapter);
        groupAdapter.notifyDataSetChanged();
    }

    @Override
    protected void onDestroy() {
        if (syncListener != null) {
            HXSDKHelper.getInstance().removeSyncGroupListener(syncListener);
            syncListener = null;
        }
        super.onDestroy();
        instance = null;
    }

    public void refresh() {
        if (groupListView != null && groupAdapter != null) {
            grouplist = EMClient.getInstance().groupManager().getAllGroups();
            groupAdapter = new GroupAdapter(GroupsActivity.this, 1, grouplist);
            groupListView.setAdapter(groupAdapter);
            groupAdapter.notifyDataSetChanged();
        }
    }

    /**
     * 返回
     * 
     * @param view
     */
    public void back(View view) {
        finish();
    }
}
